import Taro, { Component } from '@tarojs/taro'
import {View, Text, Image, Canvas} from '@tarojs/components'
import { connect } from '@tarojs/redux'
import {AtButton} from "taro-ui";
import drawQrcode from "weapp-qrcode";
import './unpay.styl'
import {IMAGE_HOST} from "../../constants/server"
import {queryOrderDetail, asyncCancelOrder} from '../../api/order'
import unpayImg from '../../assets/images/order/unpay.png'


@connect(({ cart, address, coupon, user, shop }) => ({
  cart, address, coupon, user, shop
}), () => ({
}))
class Settle extends Component {
  constructor () {
    super(...arguments)
    this.state = {
      address: null, // 地址对象
      products: [], // 商品
      code: '',
      created_at: '',
      total_amount: 0,
      total_money: 0,
      user_money: 0,
      show_qrcode: false
    }
  }
    config = {
    navigationBarTitleText: '待支付'
  }

  // 下拉刷新
  onPullDownRefresh () {
    Taro.stopPullDownRefresh()
  }

  // 加载商品
  loadOrder () {
    const {token} = this.props.user
    const {order_id} = this.$router.params // 订单id
    queryOrderDetail(token, order_id).then(({status, data}) => {
      console.log(status, data)
      if (!status) {
        Taro.showToast({
          title: '获取失败',
          icon: 'none'
        })
        return
      }
      const {products, address, code, created_at, total_amount, total_money, user_money} = data
      this.setState({
        products,
        address,
        code,
        created_at,
        total_amount,
        total_money,
        user_money
      })
    })
  }

  // 取消订单
  onCancel () {
    const {token} = this.props.user
    const {code} = this.state
    asyncCancelOrder(token, code)
      .then(({status}) => {
        if (!status) {
          throw '操作失败'
        }
        this.loadOrder()
      })
  }

  // 确认订单
  onConfirm () {
    const {order_id} = this.$router.params // 订单id
    this.setState({
      show_qrcode: true
    })
    setTimeout(async () => {
      // 设置屏幕比例
      const res = await Taro.getSystemInfo();
      const scale = res.screenWidth / 375;
      drawQrcode({
        width: 200 * scale,
        height: 200 * scale,
        canvasId: 'myQrcode',
        _this: this.$scope,
        text: String(order_id)
      });
    }, 200)
  }

  // 关闭二维码
  onCloseQR (e) {
    e.stopPropagation()
    e.preventDefault()
    this.setState({
      show_qrcode: false
    })
    this.loadOrder()
  }

  // 阻止穿透点击
  onStopClick = (e) => {
    e.stopPropagation()
    e.preventDefault()
  }

  componentWillReceiveProps () {
    // console.log(this.props, nextProps)
  }
  componentDidMount () {
  }
  componentWillUnmount () { }

  componentDidShow () {
  this.loadOrder()
  }

  componentDidHide () { }

  render () {
    const { products, address, code, created_at, total_amount, total_money, user_money } = this.state

    // 商品列表
    const renderProducts = products.map((product, index) => {
      return (<View key={index} className='order-item-product'>
        <Image
          className='order-item-product__thumb'
          style='background: #fff;'
          src={product.product_thumb ? (IMAGE_HOST + product.product_thumb) : 'https://img.icons8.com/dusk/64/000000/raspberry.png'}
        />
        <View className='order-item-product__info'>
          <View className='order-item-product__name'>{product.product_name}</View>
          <View className='order-item-product__price'>￥{parseFloat(product.product_price / 100).toFixed(2)}</View>
        </View>
        <View className='order-item-product__action'>
        </View>
        <View className='order-item-product__num'>
          x{product.product_num}
        </View>
      </View>)
    })



    return (
      <View className='settle-unpay'>
        {/*收货地址*/}
        <View className='address'>
          <Image src={unpayImg} className='address-logo' />
          {!address && <View className='address-info'>请尽快到点自取，订单为您保留4小时</View>}
          {address && <View className='address-info'>收货地址：{address.truename} {address.phone}</View>}
          {address && <View className='address-info'>{address.address}</View>}
        </View>

        {/* 商品列表 */}
        <View className='order-products'>
          <View className='order-products-header'>商品信息</View>
          <View className='order-products-list'>
            {renderProducts}
          </View>
        </View>
        {/*订单信息*/}
        <View className='order-info'>
          <View className='order-info-header'>订单信息</View>
          <View className='order-info-item'>
            <View className='left'>订单编号</View>
            <View className='right'>{code}</View>
          </View>
          <View className='order-info-item'>
            <View className='left'>创建时间</View>
            <View className='right'>{created_at}</View>
          </View>
        </View>

        {/*支付信息*/}
        <View className='order-pay'>
          <View className='order-pay-item'>
            <View className='left'>商品总价</View>
            <View className='right'>￥{parseFloat(total_amount / 100).toFixed(2)}</View>
          </View>
          <View className='order-pay-item'>
            <View className='left'>余额支付</View>
            <View className='right'>￥{parseFloat(user_money / 100).toFixed(2)}</View>
          </View>
          <View className='order-pay-item'>
            <View className='left'>商品应付</View>
            <View className='right'>￥{parseFloat(total_money / 100).toFixed(2)}</View>
          </View>
        </View>

        {/*底部*/}
        <View className='footer'>
          <View className='footer-cancel' onClick={this.onCancel.bind(this)}><Text>取消订单</Text> </View>
          <View className='footer-confirm' onClick={this.onConfirm.bind(this)}><Text>确认收货</Text> </View>
        </View>
        {this.state.show_qrcode && <View className='qrcode_model' onClick={this.onStopClick}>
          <Canvas className='scanCode' canvasId='myQrcode' />
          <AtButton type='primary' size='normal' onClick={this.onCloseQR.bind(this)}>关闭</AtButton>
        </View>}
      </View>
    )
  }
}

export default Settle
